<script setup>
import { ref, computed } from 'vue';
import { useDocumentStore } from '@/stores/documentStore';
import CreateCirculationForm from '@/components/document/CreateCirculationForm.vue';
import { ElMessage, ElMessageBox } from 'element-plus';
// 检查是否缺少 Quill 的 CSS 文件
// 在 main.js 或组件中需要引入：
import '@vueup/vue-quill/dist/vue-quill.snow.css'
import '@vueup/vue-quill/dist/vue-quill.bubble.css'

const store = useDocumentStore();

// 弹窗控制
const showCreateDialog = ref(false);
const showDraftsDialog = ref(false);
const showInboxDialog = ref(false);

// 当前编辑的草稿 ID
const editingDraftId = ref(null);

// 表单数据（用于编辑时回填）
const form = ref({
  title: '',
  content: '',
  recipientIds: []
});

// 计算属性
const drafts = computed(() => store.getDrafts());
const outboxDocuments = computed(() => store.getOutbox());
const inboxDocuments = computed(() => store.getInbox());

// 未读消息数量
const unreadCount = computed(() => {
  return inboxDocuments.value.filter(doc =>
      doc.readStatus.some(rs => rs.userId === store.currentUser.value.id && !rs.read)
  ).length;
});

// 新建草稿（打开空表单）
const handleCreateNew = () => {
  editingDraftId.value = null;
  form.value = { title: '', content: '', recipientIds: [] };
  showCreateDialog.value = true;
};

// 保存草稿（新建或更新）
const handleSaveDraft = (formData) => {
  if (editingDraftId.value) {
    // 更新已有草稿
    const success = store.updateDraft(editingDraftId.value, formData);
    if (success) {
      ElMessage.success('草稿已更新');
      editingDraftId.value = null;
    } else {
      ElMessage.error('更新失败');
    }
  } else {
    // 创建新草稿
    const result= store.saveDraft({
      title: formData.title,
      content: formData.content,
      recipientIds: formData.recipientIds
    });
    if (result) {
      ElMessage.success('草稿已保存');
    } else {
      ElMessage.error('保存失败');
    }
  }
  showCreateDialog.value = false;
};

// 发布草稿
const handlePublishDraft = (draftId) => {
  const success = store.publishDraft(draftId);
  if (success) {
    ElMessage.success('文档已发布');
  } else {
    ElMessage.error('发布失败');
  }
};

// 删除草稿
const handleDeleteDraft = (draftId) => {
  ElMessageBox.confirm('确定要删除该草稿吗？', '删除草稿', {
    type: 'warning',
    confirmButtonText: '删除',
    cancelButtonText: '取消'
  }).then(() => {
    const success = store.deleteDraft(draftId);
    if (success) {
      ElMessage.success('草稿已删除');
    } else {
      ElMessage.error('删除失败');
    }
  }).catch(() => {
    // 用户取消
  });
};

// 编辑草稿
const handleEditDraft = (draft) => {
  editingDraftId.value = draft.id;
  form.value = {
    title: draft.title,
    content: draft.content,
    recipientIds: draft.receivers.map(r => r.id)
  };
  showCreateDialog.value = true;
};
</script>

<template>
  <div class="dashboard">
    <!-- 主要内容区域 -->
    <main class="main-content">
      <!-- 操作按钮组 -->
      <div class="action-buttons">
        <el-button type="primary" @click="handleCreateNew">编辑信息</el-button>
        <el-button type="warning" @click="showDraftsDialog = true">草稿箱</el-button>
        <el-button type="success" @click="showInboxDialog = true">
          收件箱
          <span v-if="unreadCount > 0" class="badge">{{ unreadCount }}</span>
        </el-button>
      </div>


      <!-- 发件箱表格 -->
      <div class="document-table">
        <div class="table-header">
          <div class="card-header">
            <span>已发消息</span>
          </div>
        </div>
        <el-table :data="outboxDocuments" style="width: 100%">
          <el-table-column prop="title" label="标题" />
          <el-table-column prop="circulationTime" label="发布时间" width="160" />
          <el-table-column prop="sender.name" label="发布人" width="120" />
          <el-table-column label="状态" width="100">
            <template #default="scope">
              <el-tag :type="scope.row.status === 'completed' ? 'success' : 'warning'">
                {{ scope.row.status === 'completed' ? '已读' : '未读' }}
              </el-tag>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </main>

    <!-- 信息发送 / 编辑草稿 弹窗 -->
    <el-dialog
        v-model="showCreateDialog"
        :title="editingDraftId ? '编辑草稿' : '信息编辑'"
        width="40%"
        :close-on-click-modal="false"
        :destroy-on-close="true"
    >
      <CreateCirculationForm
          :initial-data="form"
          @submit="handleSaveDraft"
          @cancel="showCreateDialog = false"
      />
    </el-dialog>

    <!-- 草稿箱弹窗 -->
    <el-dialog
        v-model="showDraftsDialog"
        title="草稿箱"
        width="70%"
        :close-on-click-modal="false"
    >
      <el-table :data="drafts" style="width: 100%">
        <el-table-column prop="title" label="标题" />
        <el-table-column prop="circulationTime" label="创建/修改时间" width="160" />
        <el-table-column label="状态" width="100">
          <template #default>
            <el-tag type="info">草稿</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="220">
          <template #default="scope">
            <el-button
                size="small"
                type="primary"
                @click="handleEditDraft(scope.row)"
            >
              编辑
            </el-button>
            <el-button
                size="small"
                type="success"
                @click="handlePublishDraft(scope.row.id)"
            >
              发布
            </el-button>
            <el-button
                size="small"
                type="danger"
                @click="handleDeleteDraft(scope.row.id)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>

    <!-- ✉️ 收件箱弹窗 -->
    <el-dialog
        v-model="showInboxDialog"
        title="收件箱"
        width="60%"
        :close-on-click-modal="false"
    >
      <el-table :data="inboxDocuments" style="width: 100%">
        <el-table-column prop="title" label="标题" />
        <el-table-column prop="circulationTime" label="发布时间" width="160" />
        <el-table-column prop="sender.name" label="发布人" width="120" />
        <el-table-column label="状态" width="100">
          <template #default="scope">
            <el-tag :type="scope.row.status === 'completed' ? 'success' : 'warning'">
              {{ scope.row.status === 'completed' ? '已读' : '未读' }}
            </el-tag>
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>

    <!--  查看公文详情弹窗 -->
    <el-dialog
        v-model="showDetailDialog"
        :title="currentDocument?.title"
        width="60%"
        :close-on-click-modal="false"
    >
      <div class="document-detail">
        <p><strong>发布人：</strong>{{ currentDocument?.sender.name }}</p>
        <p><strong>发布时间：</strong>{{ currentDocument?.circulationTime }}</p>
        <p><strong>接收人：</strong>{{ currentDocument?.receivers.map(r => r.name).join('、') }}</p>

        <div class="content-box">
          <strong>内容：</strong>
          <div class="content-text">{{ currentDocument?.content }}</div>
        </div>

        <!-- 附件展示 -->
        <div v-if="currentDocument?.attachments?.length" class="attachments-section">
          <strong>附件：</strong>
          <div class="attachment-list">
            <div
                v-for="(file, index) in currentDocument.attachments"
                :key="index"
                class="attachment-item"
            >
              <!-- 文件名 + 下载按钮 -->
              <span class="attachment-name">{{ file.name }}</span>
              <span class="attachment-meta">
                ({{ formatFileSize(file.size) }})
              </span>

              <!-- 预览或下载按钮 -->
              <el-button
                  size="small"
                  type="primary"
                  plain
                  @click="previewOrDownload(file)"
              >
                {{ canPreview(file) ? '预览' : '下载' }}
              </el-button>
            </div>
          </div>
        </div>

        <!-- 预览弹窗（图片/PDF） -->
        <el-dialog
            v-model="showPreviewDialog"
            :title="previewFile?.name"
            width="80%"
            :close-on-click-modal="true"
            append-to-body
        >
          <div class="preview-content">
            <img
                v-if="previewFile && isImage(previewFile)"
                :src="previewFile.url"
                alt="附件预览"
                style="max-width: 100%; max-height: 70vh; margin: 0 auto; display: block;"
            />
            <iframe
                v-else-if="previewFile && isPDF(previewFile)"
                :src="previewFile.url"
                style="width: 100%; height: 600px; border: none;"
                frameborder="0"
            ></iframe>
            <p v-else>当前文件不支持预览，请下载查看。</p>
          </div>
        </el-dialog>
      </div>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="showDetailDialog = false">关闭</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped>
.dashboard {
  min-height: 100vh;
  background: #f5f7fa;
  font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif;
  padding:0;
}

/* 主要内容区域 */
.main-content {
  width: 100%;
  padding: 24px 40px;
  max-width: 1600px;
  margin: 0 auto;
  box-sizing: border-box;
}

/* 操作按钮组 */
.action-buttons {
  align-items: center;
  margin-bottom: 24px;
  display: flex;
  gap: 12px;
  padding: 16px;
  background: #fff;
  border-radius: 8px;
}

/* 表格卡片样式 */
.document-table {
  width: 100%;
  background: #fff;
  border: none;
  box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
  border-radius: 8px;
  overflow: hidden;
}

.table-header {
  padding: 16px 24px;
  border-bottom: 1px solid #f0f2f5;
  font-size: 18px;
  font-weight: 600;
  color: #303133;
}

:deep(.el-table) {
  border: none !important; /* 清除表格默认边框 */
}

/* 表格单元格内边距 */
:deep(.el-table .cell) {
  padding: 14px 12px;
  font-size: 14px;
}

/* 表格行hover效果 */
:deep(.el-table__row:hover > td) {
  background-color: #f7f8fa !important;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .app-header {
    padding: 16px 20px;
  }

  .app-header h1 {
    font-size: 20px;
  }

  .main-content {
    padding: 16px;
  }

  .action-buttons {
    flex-direction: column;
  }

  .document-table {
    margin-bottom: 16px;
  }
}

@media (max-width: 480px) {
  .dashboard {
    font-size: 14px;
  }

  .action-buttons {
    gap: 8px;
  }

  :deep(.el-table .cell) {
    padding: 8px 4px;
    font-size: 14px;
  }
}

/* 徽章样式 */
.badge {
  display: inline-block;
  background-color: red;
  color: white;
  border-radius: 50%;
  padding: 2px 6px;
  font-size: 12px;
  line-height: 1;
  position: relative;
  top: -8px;
  left: 4px;
}
</style>
